<?php

declare(strict_types=1);
/**
 * This file is part of Hyperf.
 *
 * @link     https://www.hyperf.io
 * @document https://hyperf.wiki
 * @contact  group@hyperf.io
 * @license  https://github.com/hyperf/hyperf/blob/master/LICENSE
 */

namespace App\Controller\Admin\Sys;

use App\Controller\AbstractController;
use App\Middleware\AuthMiddleware;
use App\Model\Comment;
use Hyperf\HttpServer\Annotation\Controller;
use Hyperf\HttpServer\Annotation\DeleteMapping;
use Hyperf\HttpServer\Annotation\GetMapping;
use Hyperf\HttpServer\Annotation\Middlewares;

#[Middlewares([AuthMiddleware::class])]
#[Controller]
class CommentController extends AbstractController
{
    #[GetMapping(path: '/sys/comment/list')]
    public function list()
    {
        $pageNum = $this->request->input('pageNum', 1);
        $pageSize = $this->request->input('pageSize', 10);
        $list = Comment::query()->select('id', 'article_id', 'user_id', 'user_id as userId', 'reply_user_id', 'parent_id', 'parent_id as parentId', 'content', 'like_count', 'is_stick as isStick', 'ip', 'browser', 'system', 'ip_source as ipSource', 'create_time as createTime')
            ->with(['user','replyUser','article'])
            ->forPage($pageNum, $pageSize)->get();
        $comments = $list->toArray();
        foreach ($comments as $index => $comment) {
            $comments[$index]['avatar'] = $comment['user']['avatar'];
            $comments[$index]['nickname'] = $comment['user']['nickname'];
            unset($comments[$index]['user']); // 可选：移除整个 user 对象

            $comments[$index]['articleTitle'] = $comment['article']['title'] ?? '';
            unset($comments[$index]['article']); // 可选：移除整个 article 对象

            $comments[$index]['replyNickname'] = $comment['reply_user']['nickname'] ?? '';
            unset($comments[$index]['reply_user']); // 可选：移除整个 replyUser 对象
        }

        // 返回树结构的评论
        $data['searchCount'] = true;
        $data['current'] = (int) $pageNum;
        $data['size'] = (int) $pageSize;
        $data['total'] = Comment::query()->count();
        $data['records'] = $comments;
        return success($data);
    }

    #[DeleteMapping(path: '/sys/comment/delete/{ids}')]
    public function delete($ids)
    {
        Comment::query()->whereIn('id', explode(',', $ids))->delete();
        return success();
    }
}
